import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { PostService } from '../API/PostService';
import { CustomLoading } from '../components/UI/Loading/CustomLoading';
import { useFetching } from '../hooks/useFetching';

export const PostIdPage = () => {
  const param = useParams();
  const [post, setPost] = useState({});
  const [comments, setComments] = useState([]);
  const [fetchPostById, isLoading, error] = useFetching(async (id) => {
    const response = await PostService.getById(id);
    setPost(await response.json());
  });
  const [fetchComments, isCommentsLoading, commentsError] = useFetching(async (id) => {
    const response = await PostService.getCommentsByPostId(id);
    setComments(await response.json());
  });

  useEffect(() => {
    fetchPostById(param.id);
    fetchComments(param.id);
  }, []);

  return (
    <div>
      {isLoading ? (
        <CustomLoading />
      ) : (
        <div>
          <h2 className="header__post">
            {post.id}. {post.title}
          </h2>
          <br />
          <p className="post__content">{post.body}</p>
        </div>
      )}

      <div>
        <h3 className='header mt30'>Комментарии</h3>
        {isCommentsLoading ? (
        <CustomLoading />
      ) : (
        <div>
          {comments.map(comment => (
            <div key={comment.id} className='mt30'>
              <span>Автор: <b>{comment.name}</b></span>
              <br />
              <span>Почта: <i>{comment.email}</i></span>
              <p>{comment.body}</p>
              <hr />
            </div>
          ))}
        </div>
      )}
      </div>
    </div>
  );
};
